#include "vector_processor.h"
#include "log.h"
#include "protocol.h"
#include "protocal.h"
#include "comm_enum.h"
#include "vector.pb.h"
#include <arpa/inet.h>

VectorProcessor::VectorProcessor(){
    uds_client_ = new VecUDSClient();
}

VectorProcessor::~VectorProcessor(){
    if(NULL == uds_client_){
        delete uds_client_;
    }
}

bool VectorProcessor::InitVectorService(std::string vector_socket_dir){
    log_info("vector_socket_dir:%s,", vector_socket_dir.c_str());
    return uds_client_->Connect(vector_socket_dir.c_str());
}

int VectorProcessor::SendToVectorService(char* buffer, int length, int cmd_type, VectorRsp& vector_add_rsp){
    int packet_len = length + sizeof(CPacketHeader);
    char *transfer_packet = new char[packet_len];
    if (transfer_packet == NULL){
        log_error("no new memory for packet");
        return -RT_NO_MEMORY;
    }

    CPacketHeader *header = (CPacketHeader *)transfer_packet;
    header->magic = htons(PROTOCOL_MAGIC);
    header->cmd = htons(cmd_type);
    header->len = htonl(length);
    memcpy(transfer_packet + sizeof(CPacketHeader), buffer, length);
    int recv_len = 0;
    char* recv_buffer = uds_client_->SendAndRecv(transfer_packet , packet_len , recv_len);
    if(NULL != transfer_packet){
        delete [] transfer_packet;
    }

    if(recv_buffer != NULL && recv_len != 0){
        bool b_ret = vector_add_rsp.ParseFromArray(recv_buffer, recv_len);
        if(false == b_ret){
            log_error("ParseFromArray got an error");
            return -RT_PARSE_ARRAY_ERROR;
        }
        free(recv_buffer);
        return 0;
    } else {
        log_error("recv_buffer is null!");
        return -RT_RECV_VECTOR_ERROR;
    }
    return 0;
}